package com.hjq.fcloud.ui.activity

import android.content.Context
import android.content.Intent
import android.text.InputFilter
import android.text.InputType
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import com.blankj.utilcode.util.TimeUtils
import com.hjq.base.BaseDialog
import com.hjq.fcloud.R
import com.hjq.fcloud.http.api.ProjectImageUploadAddApi
import com.hjq.fcloud.http.api.ProjectImageUploadDeleteApi
import com.hjq.fcloud.http.api.ProjectImageUploadDetailApi
import com.hjq.fcloud.http.api.ProjectImageUploadDetailBean
import com.hjq.fcloud.http.api.ProjectImageUploadEndDetailApi
import com.hjq.fcloud.http.api.ProjectImageUploadStartDetailApi
import com.hjq.fcloud.http.model.HttpData
import com.hjq.fcloud.jump.CommonJumpBean
import com.hjq.fcloud.ktx.ViewKtx.setVisibility
import com.hjq.fcloud.other.SelectedImageViewHelper
import com.hjq.fcloud.other.SelectedVideoHelper
import com.hjq.fcloud.ui.dialog.MenuDialog
import com.hjq.fcloud.ui.dialog.MessageDialog
import com.hjq.fcloud.utils.AppConfigUtils
import com.hjq.fcloud.utils.InputFilterMinMax
import com.hjq.fcloud.widget.ImageUploadView
import com.hjq.fcloud.widget.VerticalInputView
import com.hjq.fcloud.widget.VideoUploadView
import com.hjq.http.EasyHttp
import com.hjq.http.body.JsonBody
import com.hjq.http.config.IRequestApi
import com.hjq.http.listener.HttpCallback
import com.hjq.widget.layout.SettingBar
import kotlinx.android.synthetic.main.activity_project_image_upload.bottomView
import kotlinx.android.synthetic.main.activity_project_image_upload.rootView
import kotlinx.android.synthetic.main.activity_project_image_upload.statusLayout
import kotlinx.android.synthetic.main.activity_project_image_upload.titleBar
import okhttp3.Call


/**
 * 形象进度上传-新增
 */
open class ProjectImageUploadAddActivity : BaseDetailActivity() {

    companion object {
        const val INTENT_IN_ITEM = "item"

        //形象进度类型 1起点2过程3终点
        const val TYPE_PROGRESS = 2
        const val TYPE_PROGRESS_START = 1
        const val TYPE_PROGRESS_END = 3

        //起点形象进度图片、视频
        const val KEY_IMAGE_START = "fnc-1-1"
        const val KEY_VIDEO_START = "fnc-1-2"

        //终点形象进度图片、视频
        const val KEY_IMAGE_END = "fnc-3-1"
        const val KEY_VIDEO_END = "fnc-3-2"

        //过程形象进度图片、视频、资料
        const val KEY_IMAGE_PROGRESS = "fnc-2-1"
        const val KEY_VIDEO_PROGRESS = "fnc-2-2"
        const val KEY_IMAGE_MATERIAL_PROGRESS = "fnc-2-3"

        fun start(ac: Context, jumpBean: CommonJumpBean) {
            var intent = Intent(ac, ProjectImageUploadAddActivity::class.java)
            intent.putExtra(INTENT_IN_ITEM, jumpBean)
            ac.startActivity(intent)
        }
    }

    //选中的需求
    val selectProjectBean by lazy { AppConfigUtils.getSelectProjectItemBean() }

    private var mDetail: ProjectImageUploadDetailBean? = null

    //true是详情，false是新增
    private val isDetail by lazy { commonJumpBean?.bizId != null }

    //是否详情编辑状态
    private var isDetailEdit: Boolean = false

    //item view
    private lateinit var numberSb: SettingBar
    private lateinit var nameSb: SettingBar
    private lateinit var bidPackageSb: SettingBar

    private lateinit var timeSb: SettingBar
    private lateinit var progressVerticalInputView: VerticalInputView
    private lateinit var financingRatioSb: SettingBar
    private lateinit var imageUploadView: ImageUploadView
    private lateinit var videoUploadView: VideoUploadView
    private lateinit var visaImageUploadView: ImageUploadView

    //形象进度图片
    var imageSelectedImageViewHelper = SelectedImageViewHelper()

    //形象进度视频
    var imageSelectedVideoViewHelper = SelectedVideoHelper()

    //签证资料图片
    var visaImageSelectedImageViewHelper = SelectedImageViewHelper()

    override fun getStateLayout(): View? {
        return statusLayout
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_project_image_upload
    }

    override fun initData() {}

    override fun initView() {
        titleBar.setTitle(getShowTitle())

        if (isDetail) {
            getServerDetail()
        } else {
            addChildViews()
        }
        setRightView()
    }

    fun getShowTitle(): String {
        var type = getType()
        if (type == TYPE_PROGRESS) {
            return "形象进度过程登记"
        } else if (type == TYPE_PROGRESS_START) {
            return "形象进度起点登记"
        } else {
            return "形象进度终点登记"
        }
    }

    /**
     * 获取形象进度类型
     */
    open fun getType(): Int {
        return TYPE_PROGRESS
    }

    private fun getServerDetail() {
        showAppLoading()

        var parms = HashMap<String, Any?>()
        var type = getType()
        if (type == TYPE_PROGRESS) {
            parms.put("id", commonJumpBean?.bizId)
        } else {
            parms.put("fnc_id", selectProjectBean?.selectFncItemBean?.id)
        }
        parms.put("type", type)

        var api: IRequestApi = ProjectImageUploadDetailApi()
        if(type == TYPE_PROGRESS_START){
            api = ProjectImageUploadStartDetailApi()
        }else if(type == TYPE_PROGRESS_END){
            api = ProjectImageUploadEndDetailApi()
        }
        EasyHttp.post(this)
            .api(api)
            .body(JsonBody(parms))
            .request(object : HttpCallback<HttpData<ProjectImageUploadDetailBean>?>(this) {
                override fun onStart(call: Call?) {}
                override fun onSucceed(data: HttpData<ProjectImageUploadDetailBean>?) {
                    mDetail = data?.getData()
                    addChildViews()
                }

                override fun onEnd(call: Call?) {
                    super.onEnd(call)
                    showAppContent()
                }
            })
    }

    private fun setRightView() {
        if (isDetail && !isDetailEdit) {
            titleBar.setRightIcon(R.drawable.ic_point)
            titleBar.rightView.setOnClickListener { showMeauDialog() }
        } else {
            titleBar.setRightIcon(null)
        }
    }

    private fun showMeauDialog() {
        var data = getRightMeauDialogData()
        MenuDialog.Builder(this)
            .setList(data)
            .setListener(object : MenuDialog.OnListener<String> {

                override fun onSelected(dialog: BaseDialog?, position: Int, data: String) {
                    if (position == 0) {
                        isDetailEdit = !isDetailEdit
                        initView()
                    } else if (position == 1) {
                        MessageDialog.Builder(activity) // 标题可以不用填写
                            .setMessage("确认删除?") // 确定按钮文本
                            .setConfirm(getString(R.string.common_confirm)) // 设置 null 表示不显示取消按钮
                            .setCancel(getString(R.string.common_cancel)) // 设置点击按钮后不关闭对话框
                            .setListener(object : MessageDialog.OnListener {
                                override fun onConfirm(dialog: BaseDialog?) {
                                    requestServerDelete()
                                }
                            })
                            .show()
                    }
                }
            })
            .show()
    }

    private fun getRightMeauDialogData(): MutableList<String> {
        var data = mutableListOf<String>()
        data.add("编辑")
        data.add("删除")
        return data
    }

    private fun addChildViews() {
        showAppContent()
        rootView.removeAllViews()
        let {
            numberSb = SettingBar(context)
            numberSb.apply {
                setLeftText("需求编号")
                setRightTextHint("请选择融资需求")
                setRightText(if (isDetail) mDetail?.fnc?.code else selectProjectBean?.selectFncItemBean?.code)
            }
            rootView.addView(numberSb)
        }

        let {
            nameSb = SettingBar(context)
            nameSb.apply {
                setLeftText("项目名称")
                setRightText(if (isDetail) mDetail?.fnc?.project?.project_name else selectProjectBean?.project_name)
            }
            rootView.addView(nameSb)
        }

        let {
            bidPackageSb = SettingBar(context)
            bidPackageSb.apply {
                setLeftText("标段名称")
                setRightText(if (isDetail) mDetail?.fnc?.sect?.sect_name else selectProjectBean?.selectFncItemBean?.sect_name)
            }
            rootView.addView(bidPackageSb)
        }

        let {
            timeSb = SettingBar(context)
            timeSb.apply {
                setLeftText("录入时间")
                setRightText(mDetail?.create_time)
                if (isAddOrEdit()) {
//                    setRightDrawable(R.drawable.ic_calendar)
                    var localDate =
                        TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd"))
                    setRightText(localDate)
                }
            }
            rootView.addView(timeSb)
        }

        let {
            progressVerticalInputView = VerticalInputView(context)
            progressVerticalInputView.apply {
                if (isAddOrEdit()) {
                    getSettingBar().setLeftDrawable(R.drawable.ic_star)
                }
                getSettingBar().setLeftText("形象进度")
                getCommonInPutView().setInPutText(mDetail?.progress, isAddOrEdit())
            }
            rootView.addView(progressVerticalInputView)
        }

        let {
            if (getType() == TYPE_PROGRESS) {
                if (isAddOrEdit()) {
                    financingRatioSb =
                        layoutInflater.inflate(R.layout.layout_financing_ratio, null) as SettingBar
                } else {
                    financingRatioSb = layoutInflater.inflate(
                        R.layout.layout_financing_ratio_detail,
                        null
                    ) as SettingBar
                }
                financingRatioSb.apply {
                    setRightText(mDetail?.percentage)
                    if (isAddOrEdit()) {
                        setLeftDrawable(R.drawable.ic_star)
                        getRightView().apply {
                            var editText = this as EditText
                            inputType = InputType.TYPE_CLASS_NUMBER
                            editText.setFilters(arrayOf<InputFilter>(InputFilterMinMax(0f, 100f)))
                        }
                    }
                }
                rootView.addView(financingRatioSb)
            }
        }

        let {
            var fileList = mDetail?.files?.get(getKeyByImage())
            imageUploadView = ImageUploadView(context)
            imageUploadView.apply {
                getSettingBar().setLeftText("上传形象进度照片")
                setCanEdit(isAddOrEdit())
                setTips("现场形象进度上传图片需包含：\n1.形象进度总貌；\n2.进度局部图片；\n3.进度对应部位的明显标志")
                imageSelectedImageViewHelper.initSelectedImageView(
                    this@ProjectImageUploadAddActivity,
                    getSelectedImageView(),
                    IMAGE_MAX_SELECT
                )
                imageSelectedImageViewHelper.setData(fileList)
            }
            rootView.addView(imageUploadView)
        }

        let {
            var fileList = mDetail?.files?.get(getKeyByVideo())
            videoUploadView = VideoUploadView(context)
            videoUploadView.apply {
                getSettingBar().setLeftText("上传形象进度视频")
                setCanEdit(isAddOrEdit())
                getSettingBar().setLeftDrawable(null)
                setTips("现场形象进度上传视频需包含：形象进度总貌")
                imageSelectedVideoViewHelper.initSelectedVideoView(
                    this@ProjectImageUploadAddActivity,
                    getSelectedImageView()
                )
                imageSelectedVideoViewHelper.setData(fileList)
            }
            rootView.addView(videoUploadView)
        }

        let {
            if (getType() == TYPE_PROGRESS) {
                var fileList = mDetail?.files?.get(KEY_IMAGE_MATERIAL_PROGRESS)
                visaImageUploadView = ImageUploadView(context)
                visaImageUploadView.apply {
                    getSettingBar().setLeftText("签证资料上传")
                    setCanEdit(isAddOrEdit())
                    getSettingBar().setLeftDrawable(null)
                    setTips("")
                    visaImageSelectedImageViewHelper.initSelectedImageView(
                        this@ProjectImageUploadAddActivity,
                        getSelectedImageView(),
                        IMAGE_MAX_SELECT
                    )
                    visaImageSelectedImageViewHelper.setData(fileList)
                }
                rootView.addView(visaImageUploadView)
            }
        }

        bottomView.setVisibility(isAddOrEdit())
    }

    private fun isAddOrEdit(): Boolean {
        if (isDetailEdit || !isDetail) {
            return true
        }
        return false
    }

    fun handlerReset(view: View) {
        mDetail = null
        addChildViews()
    }

    fun handlerConfirm(view: View) {
        var parms = checkInput()
        if (parms != null) {
            var type = getType()
            parms.put("fnc_id", selectProjectBean?.selectFncItemBean?.id)
            parms.put("type", type)

            var fileMap = HashMap<String, Any>()
            //图片
            fileMap.put(
                getKeyByImage(),
                getRequestFileList(imageSelectedImageViewHelper.getData())
            )

            //视频
            var videoList = imageSelectedVideoViewHelper.getData()
            fileMap.put(getKeyByVideo(), getRequestFileList(videoList))

            if (type == TYPE_PROGRESS) {
                //签证资料图片
                fileMap.put(
                    KEY_IMAGE_MATERIAL_PROGRESS,
                    getRequestFileList(visaImageSelectedImageViewHelper.getData())
                )
            }

            parms.put("files", fileMap)
            requestServerSave(parms)
        }
    }

    private fun getKeyByVideo(): String {
        var type = getType()
        if (type == TYPE_PROGRESS) {
            return KEY_VIDEO_PROGRESS
        } else if (type == TYPE_PROGRESS_START) {
            return KEY_VIDEO_START
        } else {
            return KEY_VIDEO_END
        }
    }

    private fun getKeyByImage(): String {
        var type = getType()
        if (type == TYPE_PROGRESS) {
            return KEY_IMAGE_PROGRESS
        } else if (type == TYPE_PROGRESS_START) {
            return KEY_IMAGE_START
        } else {
            return KEY_IMAGE_END
        }
    }

    private fun checkInput(): HashMap<String, Any?>? {
        var parms = HashMap<String, Any?>()

        var progress = progressVerticalInputView.getCommonInPutView().getInPutText()
        parms.put("progress", progress)
        if (TextUtils.isEmpty(progress)) {
            showToast("请输入形象进度")
            return null
        }

        if (getType() == TYPE_PROGRESS) {
            var percentage = financingRatioSb.getRightText()?.toString()
            parms.put("percentage", percentage)
            if (TextUtils.isEmpty(percentage)) {
                showToast("请输入需求材料已形成工程实体比例")
                return null
            }
        }

        if (imageSelectedImageViewHelper.getData().size == 0) {
            showToast("请上传形象进度照片")
            return null
        }

        return parms
    }


    private fun requestServerSave(parms: HashMap<String, Any?>) {
        EasyHttp.post(this)
            .api(ProjectImageUploadAddApi())
            .body(JsonBody(parms))
            .request(object : HttpCallback<HttpData<String?>?>(this) {
                override fun onSucceed(data: HttpData<String?>?) {
                    showToast(data?.getMessage())
                    if (getType() == TYPE_PROGRESS) {
                        CommonListActivity.refershList(context)
                    } else {
                        finish()
                    }
                }
            })
    }

    private fun requestServerDelete() {
        var parms = HashMap<String, Any?>()
        parms.put("id", mDetail?.id)
        EasyHttp.post(this)
            .api(ProjectImageUploadDeleteApi())
            .body(JsonBody(parms))
            .request(object : HttpCallback<HttpData<String?>?>(this) {
                override fun onSucceed(data: HttpData<String?>?) {
                    showToast(data?.getMessage())
                    if (getType() == TYPE_PROGRESS) {
                        CommonListActivity.refershList(context)
                    } else {
                        finish()
                    }
                }
            })
    }
}